from app.sql.mysql_stock import insert_stockout_order, insert_stock_change, insert_stockout_detail
from app.utils.signUtil import sign_util
import httpx
import asyncio
from app.utils.time_util import get_three_days_ago, get_current_time

async def task_save_stockout():
    try:
        async with httpx.AsyncClient() as client:
            param = sign_util(get_three_days_ago(), get_current_time(), "0", "100")
            url = 'https://api.wangdian.cn/openapi2/stockout_order_query.php'
            
            response = await client.get(
                url=url,
                params=param,
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            
            if "stockout_list" not in data:
                raise ValueError(f"API返回格式异常: {data}")
                
            loop = asyncio.get_event_loop()
            for stockout in data["stockout_list"]:
                try:
                    # 保存出库单主信息
                    await loop.run_in_executor(None, insert_stockout_order, stockout)
                    
                    # 处理出库单明细
                    details = stockout.get("detail_list", [])
                    for detail in details:
                        detail['stockout_no'] = stockout.get('stockout_no')  # 添加关联字段
                        await loop.run_in_executor(None, insert_stockout_detail, detail)
                        
                except Exception as e:
                    print(f"处理出库单数据时出错 (出库单号可能为 {stockout.get('stockout_no')}): {e}")
                    
    except Exception as e:
        print(f"保存出库单数据时出错: {e}")
        raise

async def task_save_stock_change():
    try:
        async with httpx.AsyncClient() as client:
            param = sign_util(get_three_days_ago(), get_current_time(), "0", "100")
            url = 'https://api.wangdian.cn/openapi2/api_goods_stock_change_query.php'
            response = await client.get(
                url=url,
                params=param,
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            
            if "stock_change_list" not in data:
                raise ValueError(f"API返回格式异常: {data}")
                
            loop = asyncio.get_event_loop()
            for stock_change in data["stock_change_list"]:
                try:
                    await loop.run_in_executor(None, insert_stock_change, stock_change)
                except Exception as e:
                    print(f"处理库存变更数据时出错 (商品编号可能为 {stock_change.get('goods_no')}): {e}")
                    
    except Exception as e:
        print(f"保存库存变更数据时出错: {e}")
        raise 